﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Forest.Cat.Domain.Entities;
using System.Web;
using Forest.Cat.Domain.Services.Jobseekers;
using System.Web.Security;

namespace Forest.Cat.Domain.Services.Authentication {
    public partial class FormsAuthenticationService : IAuthenticationService {

        private readonly HttpContextBase _httpContext;
        private readonly IJobseekerService _jobseekerService;
        private readonly TimeSpan _expirationTimeSpan;

        private Jobseeker _cachedUser;

        public FormsAuthenticationService(HttpContextBase httpContext,
            IJobseekerService jobseekerService) {
            _httpContext = httpContext;
            _jobseekerService = jobseekerService;
            this._expirationTimeSpan = FormsAuthentication.Timeout;
        }

        public virtual void SignIn(Jobseeker user, bool createPersistentCookie) {
            var now = DateTime.UtcNow.ToLocalTime();

            var ticket = new FormsAuthenticationTicket(
                1 /*version*/,
               user.Email,
                now,
                now.Add(_expirationTimeSpan),
                createPersistentCookie,
               user.Email,
                FormsAuthentication.FormsCookiePath);

            var encryptedTicket = FormsAuthentication.Encrypt(ticket);

            var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
            cookie.HttpOnly = true;
            if (ticket.IsPersistent) {
                cookie.Expires = ticket.Expiration;
            }
            cookie.Secure = FormsAuthentication.RequireSSL;
            cookie.Path = FormsAuthentication.FormsCookiePath;
            if (FormsAuthentication.CookieDomain != null) {
                cookie.Domain = FormsAuthentication.CookieDomain;
            }

            _httpContext.Response.Cookies.Add(cookie);
            _cachedUser = user;
        }
        public virtual void SignOut() {
            _cachedUser = null;
            FormsAuthentication.SignOut();
        }
        public virtual Jobseeker GetAuthenticatedUser() {
            if (_cachedUser != null)
                return _cachedUser;

            if (_httpContext == null ||
               _httpContext.Request == null ||
               !_httpContext.Request.IsAuthenticated ||
               !(_httpContext.User.Identity is FormsIdentity)) {
                return null;
            }
            var formsIdentity = (FormsIdentity)_httpContext.User.Identity;
            var user = GetAuthenticatedUserFromTicket(formsIdentity.Ticket);
            if (user != null )
               _cachedUser = user;
            return _cachedUser;
            
        }

        public virtual Jobseeker GetAuthenticatedUserFromTicket(FormsAuthenticationTicket ticket) {
            if (ticket == null)
                throw new ArgumentNullException("ticket");

            var email = ticket.UserData;

            if (String.IsNullOrWhiteSpace(email))
                return null;          

            var user = _jobseekerService.GetUserByEmail(email);
            return user;
        }
    }
}
